//HTTP适配器

import 'dart:convert';

import 'package:changxindianzishangwu/http/base/ec_base_request.dart';
import 'package:changxindianzishangwu/http/core/zd_net_adapter.dart';
import 'package:http/http.dart' as http;

class HttpAdapter extends EcNetAdapter {
  @override
  Future<EcNetResponse> send<T>(EcBaseRequest request) async {
    var response;
    var error;
    var headers = request.header;
    try {
      if (request.httpMethod() == HttpMethod.GET) {
        response = await http.get(request.url(), headers: headers);
      } else if (request.httpMethod() == HttpMethod.POST) {
        response = await http.post(request.url(), headers: headers);
      } else if (request.httpMethod() == HttpMethod.DELETE) {
        response = await http.delete(request.url(), headers: headers);
      }
    } catch (e) {
      error = e;
      throw Exception(e);
    }
    if (error != null) {
      buildRes(response, request);
    }
    return buildRes(response, request);
  }
}

Future<EcNetResponse> buildRes(http.Response response, EcBaseRequest request) {
  //必须要转码  要不获取不到
  var decode = json.decode(response.body) as Map;
  return Future.value(EcNetResponse(
      data: decode, request: request, statusCode: response.statusCode));
}
